import React from 'react'
import PropTypes from 'prop-types'
import {Modal, Form, Input, Select, Avatar, Button, message} from 'antd';
import api from "../../../../api/api";
import axios from "axios";

const {Option} = Select;
const FormItem = Form.Item;

@Form.create()
class Model extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            param: {
                id: "",
                loginAccount: "",
                mobile: "",
                authorityId: "",
                orgCode: ""
            }
        };
    }

    componentDidMount() {
        console.log("dialog初始化==", this.props);
        this.props.onRef("detail", this)
        this.getAuthoritySelect();
    }

    handleOk = () => {
        this.props.form.validateFields((error, values) => {
            if (error != null) {
                return;
            }
            let {param} = this.state
            param.loginAccount = values.loginAccount
            param.mobile = values.mobile
            this.setState({param}, () => {
                this.administratorData()
            })
        })
    }
    setBaseInfo = () => {
        let data = this.props.data.gridList
        const {form} = this.props;
        console.info(this.props)
        Object.keys(form.getFieldsValue()).forEach(key => {
            const obj = {};
            if (data[key]) {
                obj[key] = data[key] || null;
            }
            form.setFieldsValue(obj);
        });
    };

    //清空form表单数据
    clearData() {
        this.props.form.resetFields();
    }

    //初始化编辑数据
    initEditData = () => {
        this.setBaseInfo()
    }

    authoritySelects = [];

    getAuthoritySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/authority/queryAuthorityInfoSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.post(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.error({content:"加载失败，请重新尝试 ！"})
                return;
            }
            let companyInfoList = res.data.data.authorityInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.authorityId;
                data.label = comData.authorityName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.authoritySelects.push(<Option key={dataList[i].key} value={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            message.error({content:"加载失败，请重新尝试 ！"})
            console.log(err);
        })

    }

    authorityChange = (value) => {
        console.info("value ==",value)
        const {param} = this.state;
        param.authorityId = value;
    }

    administratorData() {
        let url = ""
        if (this.props.data.type === 2) {
            url = api.api_URL + "/admin/logininfo/updateLoginInfo"
            let {param} = this.state
            param.id = this.props.data.gridList.id
            this.setState({param}, () => {
                this.handleAdministrator(url)
            })
        } else {
            url = api.api_URL + "/admin/logininfo/addLoginInfo"
            let {param} = this.state
            param.id = '';
            param.orgCode = localStorage.getItem("orgCode")
            this.handleAdministrator(url)
        }
    }

    //添加
    handleAdministrator(url) {
        const that = this;
        axios({
            method: 'POST',
            url: url,
            data: JSON.stringify(that.state.param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            if (response.data.code !== 1) {
                message.error({content:"失败，请重新尝试 ！"})
                return;
            }
            message.success({content:"成功！"})
            that.handleCancel()
        })
            .catch(function (error) {
                message.error({content:"失败，请重新尝试 ！"})

                console.log(error);
            })
    }

    handleCancel = e => {
        console.log(e);
        this.props.handleCancel()
    };

    render() {
        const {getFieldDecorator, getFieldError} = this.props.form
        return (
            <div>
                <Modal
                    title={this.props.data.title}
                    visible={this.props.data.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <Form name="control-ref" autoComplete="off" ref={this.formRef}
                          labelCol={{span: 4}}
                          wrapperCol={{span: 14}}>
                        <FormItem label="账号" name="loginAccount">
                            {getFieldDecorator("loginAccount", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请输入账号"
                                    }
                                ]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="手机号" name="mobile">
                            {getFieldDecorator("mobile", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请输入手机号"
                                    }
                                ]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="权限组" name="authorityId">
                            {getFieldDecorator("authorityId", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请选择权限组"
                                    }
                                ]
                            })(
                                <Select
                                    onChange={this.authorityChange} allowClear>
                                    {this.authoritySelects}
                                </Select>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Model